package com.origin.opengles_ndk

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.opengl.GLSurfaceView
import com.origin.utils.log.LogUtils
import java.io.IOException
import java.io.InputStream
import java.nio.ByteBuffer
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10

class MyGLRender : GLSurfaceView.Renderer {
    companion object {
        val SAMPLE_TYPE = 200;
        final val SAMPLE_TYPE_KEY_TRIANGLE = SAMPLE_TYPE + 0;
    }


    private val myNativeRender: MyNativeRender by lazy {
        MyNativeRender()
    }

    override fun onSurfaceCreated(gl: GL10, config: EGLConfig) {
        myNativeRender.native_OnSurfaceCreated()
    }

    override fun onSurfaceChanged(gl: GL10, width: Int, height: Int) {
    }

    override fun onDrawFrame(gl: GL10) {
        try {
            myNativeRender.native_OnDrawFrame()
        } catch (e: Exception) {
            LogUtils.json("异常 ${e.toString()}")
        }

    }

    fun setParamsInt(i: Int) {
        myNativeRender.native_SetParamsInt(i)
    }

    fun unInit() {
        myNativeRender.native_UnInit()
    }

    fun loadRGBAImage(context: Context, resId: Int): Bitmap? {
        val `is`: InputStream = context.resources.openRawResource(resId)
        val bitmap: Bitmap?
        try {
            bitmap = BitmapFactory.decodeStream(`is`)
            if (bitmap != null) {
                val bytes = bitmap.byteCount
                val buf = ByteBuffer.allocate(bytes)
                bitmap.copyPixelsToBuffer(buf)
                val byteArray = buf.array()
                // IMAGE_FORMAT_RGBA
                setImageData(0x01, bitmap.width, bitmap.height, byteArray)
            }
        } finally {
            try {
                `is`.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return bitmap
    }

   private fun setImageData(format: Int, width: Int, height: Int, bytes: ByteArray?) {
        myNativeRender.native_SetImageData(format, width, height, bytes)
    }


}